<?php

namespace MoChat\App\Client\Action\Dashboard\Tag;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Client\Contract\ClientTagContract;
use MoChat\App\Client\Contract\ClientTagGroupContract;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;

/**
 * 客户标签列表.
 * @Controller
 */
class Index extends AbstractAction
{
    /**
     * @Inject
     * @var ClientTagContract
     */
    protected $clientTagService;

    /**
     * @Inject
     * @var ClientTagGroupContract
     */
    protected $clientTagGroupService;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    protected $logger;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class)
     * })
     * @RequestMapping(path="/dashboard/clientTag/index", methods="GET")
     */
    public function handle()
    {
        $user = user();
        // 判断用户绑定企业信息
        if (!isset($user['corpIds']) || count($user['corpIds']) !== 1) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未选择登录企业，不可操作');
        }
        //不存在默认标签
        if (empty($this->clientTagGroupService->getWorkContactTagGroupsByName($user['corpIds'][0], '客户分类', ['id']))) {
            Db::beginTransaction();
            try {
                $count = $this->clientTagGroupService->countWorkContactTagGroup($user['corpIds'][0]);
                $groupId = $this->clientTagGroupService->createWorkContactTagGroup([
                    'corp_id' => $user['corpIds'][0],
                    'group_name' => '客户分类',
                    'is_default'=>1,//默认标签
                    'order' => $count,
                ]);
                $tags = [
                    [
                        'name' => 'S类',
                        'order' => 1,
                        'remark' => '',
                    ],
                    [
                        'name' => 'A类',
                        'order' => 2,
                        'remark' => '',
                    ],
                    [
                        'name' => 'B类',
                        'order' => 3,
                        'remark' => '',
                    ],
                    [
                        'name' => 'C类',
                        'order' => 4,
                        'remark' => '',
                    ],
                    [
                        'name' => 'D类',
                        'order' => 5,
                        'remark' => '',
                    ],
                ];
                foreach ($tags as &$val) {
                    $val['corp_id'] = user()['corpIds'][0];
                    $val['client_tag_group_id'] = $groupId;
                }
                unset($val);
                $this->clientTagService->createWorkContactTags($tags);
                Db::commit();
            } catch (\Throwable $e) {
                Db::rollBack();
                $this->logger->error(sprintf('%s [%s] %s', '创建默认标签失败', date('Y-m-d H:i:s'), $e->getMessage()));
                $this->logger->error($e->getTraceAsString());
            }
        }
        // 接收参数
        $searchStr = $this->request->input('searchStr');
        if (!empty($searchStr)) {
            return $this->getSearchStr($user, $searchStr);
        }

        return $this->getAll($user);
    }

    /**
     * 根据名称查询.
     */
    private function getSearchStr(array $user, string $searchStr): array
    {
        // 查询标签分组
        $group = $this->clientTagGroupService->getWorkContactTagGroupsByName($user['corpIds'][0], $searchStr, ['id', 'group_name', 'order','is_default']);
        if (empty($group)) {
            // 查询标签
            $tags = $this->clientTagService->getWorkContactTagsByCorpIdName($user['corpIds'][0], $searchStr, ['id', 'name', 'order', 'client_tag_group_id']);
            if (!empty($tags)) {
                // 标签分组id
                $groupIds = array_column($tags, 'clientTagGroupId');
                // 查询标签分组
                $groups = $this->clientTagGroupService->getWorkContactTagGroupsById($groupIds, ['id', 'group_name', 'order']);
                return $this->getTags($groups);
            }
            return [];
        }
        return $this->getTags($group);
    }

    /**
     * 查询标签.
     */
    private function getTags(array $groups): array
    {
        $count = 0;
        foreach ($groups as &$group) {
            $group['tags'] = $this->clientTagService->getWorkContactTagsByGroupIds([$group['id']], ['id', 'name', 'order', 'client_tag_group_id']);
            $count += count($group['tags']);
        }
        unset($group);
        return ['count' => $count, 'list' => $groups];
    }

    /**
     * 查询所有.
     */
    private function getAll(array $user): array
    {
        $groups = $this->clientTagGroupService->getWorkContactTagGroupsByCorpIdOrder([$user['corpIds'][0]], ['id', 'group_name', 'order','is_default']);
        return $this->getTags($groups);
    }
}
